#!/bin/bash
function usage() {
    echo "Usage: $( basename $0 ) [-h | -l <log_file> | -m <machine> | -c <apd_root> | -t <target>]"
    echo "    bitbake autosar ap demo"
    echo "    参数说明:"
    echo "    -m <machine> : build for machine, default qemux86."
    echo "    -c <apd_root>: 进入<apd_root>执行命令"
    echo "    -t <target>: build target."
    echo "    -l <log_file>: log file, default /dev/stdout"
    echo "    -h : 输出本信息"
    echo "    支持的machine:"
    for m in ${machines[@]}
    do
        if [[ "h3ulcb" == "$m" ]]
        then
            echo "        * $m (Renesas RH3 board)"
        else
            echo "        * $m"
        fi
    done
    echo "    支持的target:"
    for t in ${targets[@]}
    do
        echo "        * $t"
    done
    exit 1
}

machines=( qemux86
    qemux86-64 \
    qemuarm \
    qemuarm64 \
    intel-corei7-64 \
    h3ulcb \
    raspberrypi3 \
    raspberrypi3-64 \
    raspberrypi4 \
    raspberrypi4-64 \
)
targets=( ara-sdk \
    core-image-apd-minimal \
    core-image-apd-minimal-radar \
    core-image-apd-minimal-fusion \
    core-image-apd-minimal-radar-fusion \
    core-image-apd-devel-radar \
    core-image-apd-devel-fusion \
    core-image-apd-devel \
)

set -e
log="/dev/stdout" 
machine="qemux86"

while getopts ":hl:m:c:t:" args
do
    case "${args}" in
        l)
            log="${OPTARG}"
            ;;
        m)
            machine="${OPTARG}"
            ;;
        c)
            root="${OPTARG}"
            ;;
        t)
            target="${OPTARG}"
            ;;
        *)
            usage
            ;;
    esac
done

if [ -z "${root}" -o ! -d "${root}" ]
then
    echo "Error: invalid <apd_root>" >> ${log}
    usage
fi

if [ ! -f "${root}/yocto-layers/ara-init-build-env" ]
then
    echo "Error: invalid <apd_root>, not found ara-init-build-env" >> ${log}
    exit 1
fi

if [ -z "${target}" ]
then
    echo "Error: target not specify"
    usage
fi

# 清理全部命令行参数,否则会影响到ara-init-build-env脚本的执行
shift $#

(
  taskDesc="${target} building"
  echo "INFO $(date): start ${taskDesc}" >> "${log}" 

  cd "${root}"
  source ./yocto-layers/ara-init-build-env 
  MACHINE="${machine}" bitbake ${target}

  echo "INFO $(date): end ${taskDesc}" >> "${log}"
)
